package cn.jdemo.unsafe.theUnsafe;

import sun.misc.Unsafe;
import java.lang.reflect.Field;
/**
 * @see Unsafe#getUnsafe() 不能通过该方法直接获取到该类的实例，因为注解@CallerSensitive
 * @see Unsafe#theUnsafe 反射获取
 * @see sun.reflect.CallerSensitive 注解，表示该方法的调用，需要调用者被该方法信任
 * @date 2021/1/15
 */
public class AllInOne {
    /**
     * @see Unsafe#getUnsafe() 不能通过该方法直接获取到该类的实例，因为你的类不被该类所信任
     * @see Unsafe#theUnsafe
     * @return
     */
    public static Unsafe getTheUnasfe(){
        Class<Unsafe> unsafeClass = Unsafe.class;
        Field theUnsafeField = null;
        Unsafe theUnsafe = null;
        try {
            theUnsafeField = unsafeClass.getDeclaredField("theUnsafe");
            theUnsafeField.setAccessible(true);
            theUnsafe = (Unsafe) theUnsafeField.get(null);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return  theUnsafe;
    }
}
